<?

class Smutty_Model_Transaction {

	var $models, $errors;

	/**
	 *  constructor
	 *
	 */

	function Smutty_Model_Transaction() {
		$this->models = array();
		$this->errors = array();
		for ( $i=0; $i<func_num_args(); $i++ ) {
			$arg = func_get_arg( $i );
			array_push(
				$this->models,
				$arg
			);
		}
	}

	/**
	 *  adds one or more models to the transaction
	 *
	 *  @param [variable] model objects
	 *
	 */

	function add() {
		for ( $i=0; $i<func_num_args(); $i++ ) {
			$arg = func_get_arg( $i );
			array_push(
				$this->models,
				$arg
			);
		}
	}

	/**
	 *  checks if all the models in the transaction are valid
	 *
	 *  @return boolean
	 *
	 */

	function isValid() {
		$this->errors = array();
		foreach ( $this->models as $model )
			if ( !$model->isValid() )
				$this->errors = array_merge( $this->errors, $model->getErrors() );
		return ( !$this->errors );
	}

	/**
	 *  checks all the models in the transaction for validity
	 *  before saving them.
	 *
	 *  @return boolean
	 *
	 */

	function save() {
		if ( !$this->isValid() )
			return false;
		foreach ( $this->models as $model )
			$model->save();
		return true;
	}

	/**
	 *  returns any errors found when trying to save the transaction
	 *
	 */

	function getErrors() {
		return $this->errors;
	}

}

?>